//
//  KoiAccountingDB.swift
//  KoiAccounting
//
//  Created by 纪洪文 on 16.03.25.
//

import Foundation
import GRDB

class KoiAccountingDB {
    
    static let standard = KoiAccountingDB()
    
    private var dbQueue: DatabaseQueue!
    
    private init() {
        let fileManager = FileManager.default
        let folderURL = try! fileManager.url(for: .documentDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
        let dbURL = folderURL.appendingPathComponent("koiaccounting.sqlite")
                
        var config = Configuration()
        config.prepareDatabase { db in
//            db.trace { print("SQL:\($0)") }
        }
        
        dbQueue = try! DatabaseQueue(path: dbURL.path, configuration: config)
        createTable()
    }
    
    private func createTable() {
        // 创建账本表
        AccountingBook.createTable(dbQueue: dbQueue)
        // 创建类别表
        AccountingCategory.createTable(dbQueue: dbQueue)
        // 创建明细表
        AccountingDetail.createTable(dbQueue: dbQueue)
        // 创建记账明细视图
        AccountingDetailCombineView.createView(dbQueue: dbQueue)
        // 创建预算表
        AccountingBudget.createTable(dbQueue: dbQueue)
    }
    
    func getBookDao() -> BookDao {
        return BookDao(dbQueue:dbQueue)
    }
    
    func getCategoryDao() -> CategoryDao {
        return CategoryDao(dbQueue:dbQueue)
    }
    
    func getDetailDao() -> DetailDao {
        return DetailDao(dbQueue: dbQueue)
    }
    
    func getBudgetDao() -> BudgetDao {
        return BudgetDao(dbQueue: dbQueue)
    }
}
